#include "globalprofile.h"
#include <QDir>
#include <QTextStream>
#include "interprofiles.h"
#include <QDebug>
#include <QStringList>
#include <QCoreApplication>

#include <QStandardPaths>


QStringList GlobalProfile::acceptableVideoFormats()
{
  if (GlobalProfile::videoFormats.isEmpty()) {

    foreach (QString a, profile::interVideoFormats) {
      if (! GlobalProfile::videoFormats.contains(a))
        GlobalProfile::videoFormats.append(a);
    }

    QStringList userFormats = GlobalProfile::read_user_formats();

    foreach (QString a, userFormats) {
      if (! GlobalProfile::videoFormats.contains(a)) {
        GlobalProfile::videoFormats.append(a);
        qDebug() << "加载格式配置：" << a;
      }
    }
  }
  return GlobalProfile::videoFormats;
}

QStringList GlobalProfile::frameRates()
{
  if (GlobalProfile::userFrameRates.isEmpty()) {

    foreach (QString a, profile::interFrameRates) {
      if (! GlobalProfile::userFrameRates.contains(a))
        GlobalProfile::userFrameRates.append(a);
    }

    QStringList userRates = GlobalProfile::read_user_framerates();

    foreach (QString a, userRates) {
      if (! GlobalProfile::userFrameRates.contains(a)) {
        GlobalProfile::userFrameRates.append(a);
        qDebug() << "添加新的帧速率:" << a;
      }
    }
  }
  return GlobalProfile::userFrameRates;
}

QMap<QString, QStringList> GlobalProfile::videoCodecMap()
{
  if (GlobalProfile::vCodecMap.isEmpty()) {

    foreach (QString k, profile::interVCodecMap.keys()) {
      GlobalProfile::vCodecMap.insert(k, profile::interVCodecMap[k]);
    }

    auto userVCodecs = GlobalProfile::read_user_vcodecs();

    foreach (QString k, userVCodecs.keys()) {
      GlobalProfile::vCodecMap.insert(k, userVCodecs[k]);
      qDebug() << "添加用户视频编码：" << k << "->" << userVCodecs[k];
    }
  }
  return GlobalProfile::vCodecMap;
}

QMap<QString, QStringList> GlobalProfile::audioCodecMap()
{
  if (GlobalProfile::aCodecMap.isEmpty()) {

    foreach (QString k, profile::interACodecMap.keys()) {
      GlobalProfile::aCodecMap.insert(k, profile::interACodecMap[k]);
    }

    auto userACodecs = GlobalProfile::read_user_acodecs();

    foreach (QString k, userACodecs.keys()) {
      GlobalProfile::aCodecMap.insert(k, userACodecs[k]);
      qDebug() << "添加用户音频编码：" << k << "->" << userACodecs[k];
    }
  }
  return GlobalProfile::aCodecMap;
}


QString GlobalProfile::configDir()
{
  if (GlobalProfile::config_path.isEmpty()) {
    GlobalProfile::config_path = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
  }

  QDir c(config_path);
  if (! c.exists()) {
    c.mkpath(".");
    qDebug() << "配置文件目录未找到，正在新建:" << config_path;
  }

  return GlobalProfile::config_path;
}

QStringList GlobalProfile::read_user_formats()
{
  QString profilePath = GlobalProfile::configDir() + "/formats.txt";
  QFile f(profilePath);
  if (! f.exists()) {
    qDebug() << "输入输出格式配置文件未找到，已新建。";
    f.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream w(&f);
//    w.setCodec("UTF-8");
    w << QString("# 在这里定义可以导入或导出的文件扩展名。\n")
      << QString("# 输入的扩展名无需输入「点号」。\n")
      << QString("# 警号开头为注释。");
//      << QString("# 请保存为 UTF-8 编码。\n");
    f.close();
  };

  QStringList result = read_user_list_conf(profilePath);
  return result;
}

QStringList GlobalProfile::read_user_framerates()
{
  QString profilePath = GlobalProfile::configDir() + "/framerates.txt";
  QFile f(profilePath);
  if (! f.exists()) {
    qDebug() << "帧速率配置文件未找到，已新建。";
    f.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream w(&f);
//    w.setCodec("UTF-8");
    w << QString("# 在这里定义额外需要的帧速率。\n")
      << QString("# 每行一项，可以为小数。\n")
      << QString("# 警号开头为注释。");
//      << QString("# 请保存为 UTF-8 编码。\n");
    f.close();
  };

  QStringList result = read_user_list_conf(profilePath);
  return result;
}

QStringList GlobalProfile::read_user_list_conf(QString path)
{
  QStringList result;
  QFile f(path);
  if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
    qDebug() << "尝试读取列表格式文件:" << path;
    QTextStream r(&f);
    QString line = r.readLine();
    while (! line.isNull()) {
      QString tLine = line.trimmed();
      if ((! tLine.isEmpty()) && (! tLine.startsWith("#"))) {
        result << tLine;
        qDebug() << "读取行:" << tLine;
      }
      line = r.readLine();
    }
    f.close();
  }
  return result;
}

QMap<QString, QStringList> GlobalProfile::read_user_map_conf(QString path)
{
  QMap<QString, QStringList> result;
  QFile f(path);
  if (! f.exists()) {
    qDebug() << "文件" << path << "未找到,正在新建。";
    f.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream w(&f);
    w << QString("# 此处添加编码设置。警号开头为注释。\n")
      << QString("# 不按规定书写配置文件可能会导致奇怪的问题。")
      << QString("# 每行一条记录，编码名称与设置选项使用双冒号分隔。下面一行是一个例子。\n")
      << QString("# 超级编码::-codec:v hevc -profile:v something");
    f.close();
  }

  if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
    QTextStream r(&f);
    QString line = r.readLine();
    while (! line.isNull()) {
      QString tLine = line.simplified();
      if ((! tLine.isEmpty()) && (! tLine.startsWith("#")) && (tLine.contains("::"))) {
        QStringList record = tLine.split("::");
        QString name = record.at(0);
        QStringList options = record.at(1).split(" ");
        if (options.first().trimmed().isEmpty())
          options.removeFirst();
        result[name] = options;
        qDebug() << "读取编码记录：" << tLine;
      }
      line = r.readLine();
    }
    f.close();
  }

  return result;
}

QMap<QString, QStringList> GlobalProfile::read_user_vcodecs()
{
  QString profilePath = GlobalProfile::configDir() + "/video.txt";
  qDebug() << "尝试读取配置文件:" << profilePath;
  return read_user_map_conf(profilePath);
}

QMap<QString, QStringList> GlobalProfile::read_user_acodecs()
{
  QString profilePath = GlobalProfile::configDir() + "/audio.txt";
  qDebug() << "尝试读取配置文件:" << profilePath;
  return read_user_map_conf(profilePath);
}
